<?

//Initiate Authenticate
SecurityRedirect ();

//initiate Vars
define("PRIMARY_KEY","nobkt");
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");
$FileName       = "ais_transaction_adventry_oth.php";
$FileTemplate   = "ais_transaction_adventry_oth_form.html";
$SubHeaderTitle = "Transaction Advance - Entry Advance Other";
$TableName          = "ais_advance";
$HTMLFormName   = "AdvanceForm";
$MaxGrid        = "20";
$KTRASL     = GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("adv_id"=>"","urut"=>"0","uraian"=>"0","skada"=>"0","jumlah"=>"number");

//buildsqlfield ("$TableName", $FormFields);
//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name",1);
$FormCValue    = BuildHTMLField($FormFields,"value",1);
$jo_id = GetParam("jo_ido","");

//************ FORM ACTION **************
if (trim(GetParam("form",""))==trim($HTMLFormName)) {
    if (GetParam("FormAction","")=="Save") {
        list($FDay,$FMonth,$FYear) = explode("/",GetParam("tglbkt",""));
        $tglbkt = "$FYear-$FMonth-$FDay";
        $rate    = StrToNumber (GetParam("rate",""));
        if (trim(GetParam("nobkt",""))=="AUTO NUMBERED BY SYSTEM")  {
            $ObjNumber  = new autonumber(GetParam("tglbkt",""));
            $TransNo = $ObjNumber->GetNumber("BS");
            //FormSave($TableName, "uraian", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"debnam"=>GetParam("debnam",""),"nobkt"=>$TransNo,"tglbkt"=>"$tglbkt","curr"=>GetParam("curr",""),"kdact"=>GetParam("kdact",""),"noorder"=>GetParam("noorder",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"dk"=>"D","skada"=>GetBSParam(),"app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1","")),"adv_id");
            FormSave($TableName, "uraian", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"debnam"=>GetParam("debnam",""),"nobkt"=>$TransNo,"tglbkt"=>"$tglbkt","curr"=>GetParam("curr",""),"jo_id"=>GetParam("jo_ido",""),"noorder"=>GetParam("noorder",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"dk"=>"D","app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1",""), "bs_ref"=>"OTH", "bs_progress"=>"bs"),"adv_id");
            SetLogActivity($TransNo,"Create","");
        } else {
            $TransNo = GetParam("nobkt","");
            //FormSave($TableName, "uraian", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"debnam"=>GetParam("debnam",""),"nobkt"=>$TransNo,"tglbkt"=>"$tglbkt","curr"=>GetParam("curr",""),"kdact"=>GetParam("kdact",""),"noorder"=>GetParam("noorder",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"dk"=>"D","skada"=>GetBSParam(),"app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1","")),"adv_id");
            FormSave($TableName, "uraian", $FormFields, array("ledger"=>GetPeriod(GetParam("tglbkt","")),"debnam"=>GetParam("debnam",""),"nobkt"=>$TransNo,"tglbkt"=>"$tglbkt","curr"=>GetParam("curr",""),"jo_id"=>GetParam("jo_ido",""),"noorder"=>GetParam("noorder",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"dk"=>"D","app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1",""), "bs_ref"=>"OTH", "bs_progress"=>"bs"),"adv_id");
            SetLogActivity($TransNo,"Update","");
        }

//  UpdateHistory($TransNo,GetParam("total_trans",""));
    DeleteRecord ("txtCheck",$MaxGrid);
    header("Location: $FileName?PageMode=Form&nobkt=$TransNo");
    exit;
    }
    
    if (GetParam("FormAction","")=="Cancel BS") {
//      print "Deleted"."<br>\n";
        //$SQL = "DELETE FROM ais_advance WHERE nobkt='".GetParam("nobkt","")."' ";
        $TransNo = GetParam("nobkt","");
        $SQL = "UPDATE ais_advance SET bs_progress = 'cancel' where nobkt = '$TransNo' ";
        $DBConnection->dbc->query($SQL);
        SetLogActivity(GetParam("nobkt",""),"Update","");
        header("Location: $FileName?PageMode=Form");
        exit;
    }
    
    if (GetParam("FormAction","")=="Delete") {
//      print "Deleted"."<br>\n";
        $SQL = "DELETE FROM ais_advance WHERE nobkt='".GetParam("nobkt","")."' ";
        $DBConnection->dbc->query($SQL);
        SetLogActivity(GetParam("nobkt",""),"Update","");
        header("Location: $FileName?PageMode=Form");
        exit;
    }

}

//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";
$VerifyFields = array("nobkt"=>"ID No.","tglbkt"=>"Transaction Date","curr"=>"Currency","kdact"=>"Activity Code","noorder"=>"");
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar,array("debtur"=>"Payment To"));

if (GetParam(PRIMARY_KEY,"")) {
    $SQLCount     = "SELECT count(*) FROM `$TableName`";
    $SQLCount    .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."'";
    $Count        = $DBConnection->dbc->get_var($SQLCount);
} else $Count=0;

$NewDataStart = $Count+1;
$InitFunction = "Masking();Masking2();";
$VerifyGrids = array("uraian"=>"0","jumlah"=>"number");
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array("tglbkt"=>"date","rate"=>"number"),"2");
$JSMasks  = $Masking1.$Masking2;

Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);

//************ SET FORM MODE ***************
if (GetParam(PRIMARY_KEY,"")) {
  $FormMode = "Edit";
  $USER_CANPRINT="1";
  /*
  if (!isApproved(GetParam("nobkt",""))) $USER_CANPRINT="";
  else $USER_CANPRINT="1";*/
} else {
  $FormMode = "Add";
  $USER_CANPRINT="";
}

//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQLGrid  = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQLGrid .= " ORDER BY ".PRIMARY_KEY;
}

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************
//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Activity
$SQLAct  = "SELECT  * FROM tblactivity";

$HeaderFields = array("debnam"=>"0","nobkt"=>"0","tglbkt"=>"date","curr"=>"","rate"=>"number","debtur"=>"","kdact"=>"","app1"=>"","nmapp1"=>"","noorder"=>"");
//Leave Here Untouch
$FormCName     = BuildHTMLField($HeaderFields,"name",1);
$FormCValue    = BuildHTMLField($HeaderFields,"value",1);
$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= "WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);
$TBS->MergeBlock("receiptblk",$DBMysql,$SQLReceipt);
$TBS->MergeBlock("actblk",$DBMysql,$SQLAct);

// HTML Value
$TBS->MergeBlock("headbln",$FormCName);
if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("headblv",$DBMysql,$SQLHeader);}
else $TBS->MergeBlock("headblv",$FormCValue);


//********************************* HTML GRID *********************************************
//HTML Grid
if (strlen($SQLGrid)) $Result = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

$TBS->MergeBlock("deptblk",$DBMysql,$SQLDept);
$TBS->MergeBlock("blg",$Result);
$TBS->Show();

//*************** ACTION FUNCTION *******************
function isApproved($nobkt) {
    global $DBConnection,$TableName;
        $SQL = "SELECT app1 FROM $TableName WHERE nobkt='$nobkt' limit 1";
        return $DBConnection->dbc->get_var($SQL);
}

function FormInsert() {
    global $DBConnection,$FileName;
    $DBConnection->Insert();
    header("Location: $FileName?PageMode=Form");
    exit;
}

function FormUpdate() {
    global $DBConnection;
    $DBConnection->Update();
}

function FormDelete() {
    global $DBConnection,$FileName,$TableName;
    $DBConnection->deleteGrid("$TableName","nobkt");
    header("Location: $FileName?PageMode=Form");
    exit;
}

function FormSearch () {

}

function FormCancel () {
    global $FileName;
    header("Location: ".$FileName);
    exit;
}

function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey) {
    global $FileName, $MaxGrid, $DBConnection;
    $TotalData = $MaxGrid * 2;
    $NewDataStart = GetParam("NewData","0");
    for ($a=1;$a<=$TotalData;$a++) {
        foreach ($FormFields as $key=>$formatting) {
            if (!GetParam($keyField.$a,"")) {
                $EndOfData = 1;
                break;
            }
            $value = GetParam($key.$a,"");
            if ($formatting=="number") $value = str_replace(",","",$value);
            if ($formatting=="date") {
                list($day,$month,$year) = explode("/",$value);
                $value = "$year-$month-$day";
            }
            $DBConnection->add_data($table,$key,$value);
        }
        $rate = StrToNumber(GetParam("rate",""));
        $jmh  = StrToNumber(GetParam("jumlah".$a,""));
        $rupiah = $rate * $jmh;
        $DBConnection->add_data($table,"rupiah",$rupiah);
        if ($EndOfData) {
            break;
        }
        if (!empty($SpecialCase)) {
            foreach ($SpecialCase as $key => $value) {
            //  print "add_data($table,$key,$value);<br>";
                $DBConnection->add_data($table,$key,$value);
            }
        }
//      print "$a < $NewDataStart<br>";
        if ($a < $NewDataStart) {
             if (strlen($PrimaryKey)) {
                $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
             } else {
                $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
             }
        } else {
            $DBConnection->InsertGrid();
        }
    }
            $DBConnection->ClearData();
}
//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield) {
        global $DBConnection;
        for ($x=0;$x<count($arrayfield);$x++) {
            $DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
        }
}

function DeleteRecord ($sequence_name,$PageSize) {
    global $DBConnection,$FileName,$TableName;
    for ($x=1;$x<=$PageSize;$x++) {
        if (GetParam($sequence_name.$x,"")) {
            $DBConnection->deleteGrid("$TableName","adv_id",$sequence_name.$x);
        }
    }
}

function BuildFields ($FormFields) {
        global $DBConnection;
        $str = "";
        foreach ($FormFields as $key=>$formatting) {
            if (strlen($str)) $str .= ",$key";
            else $str = "$key";
        }
        return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
        global $DBConnection;
        $array_fields = array();
        for ($x=0;$x<$MaxGrid;$x++) {
            foreach ($FormFields as $key=>$formatting){
                $a=$x+1;
                $array_fields[$key.$a] = "$formatting";
            }
        }
        return $array_fields;
}

function UpdateHistory($nobkt,$value) {
    global $DBConnection;
    $SQL = "SELECT COUNT(*) FROM ais_history_trans WHERE entry1 = '".$nobkt."'";
    $isExist = $DBConnection->dbc->get_var($SQL);
    if ($isExist) {
        $DBConnection->dbc->query("UPDATE ais_history_trans SET amount1 = '".StrToNumber($value)."' WHERE entry1='".$nobkt."'");
    } else {
        $DBConnection->dbc->query("INSERT INTO ais_history_trans (ledger, ktrasl, entry1, amount1) VALUES ('".GetLedger()."','".GetOfficeID()."','$nobkt','".StrToNumber($value)."')");
    }
}
?>
